package org.gdstash.ui.util;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;

public class EnabledComboBox<E> extends JComboBox<E> {
    private List<ActionListener> actionListeners;
    private EnabledComboBoxRenderer<E> renderer;

    public EnabledComboBox() {
        super(new EnabledComboBoxModel());
        this.setRenderer(this.renderer = new EnabledComboBoxRenderer<E>((EnabledComboBoxModel) this.getModel()));
        super.addActionListener(new ComboListener());
        this.actionListeners = new LinkedList<ActionListener>();
    }

    public EnabledComboBox(final EnabledComboBoxModel<E> model) {
        super(model);
        this.setRenderer(this.renderer = new EnabledComboBoxRenderer<E>(model));
        super.addActionListener(new ComboListener());
        this.actionListeners = new LinkedList<ActionListener>();
    }

    @Override
    public void addActionListener(final ActionListener l) {
        this.actionListeners.add(l);
    }

    @Override
    public void removeActionListener(final ActionListener l) {
        this.actionListeners.remove(l);
    }

    @Override
    public ActionListener[] getActionListeners() {
        return (ActionListener[]) this.actionListeners.toArray();
    }

    @Override
    public void setModel(final ComboBoxModel<E> model) {
        if (!(model instanceof EnabledComboBoxModel)) {
            throw new IllegalArgumentException();
        }
        super.setModel(model);
        this.setRenderer(this.renderer = new EnabledComboBoxRenderer<E>((EnabledComboBoxModel) model));
    }

    public boolean isEnabled(final int index) {
        final EnabledComboBoxModel model = (EnabledComboBoxModel) this.getModel();
        return model.isEnabled(index);
    }

    public void setEnabled(final boolean enabled, final int index) {
        final EnabledComboBoxModel model = (EnabledComboBoxModel) this.getModel();
        model.setEnabled(enabled, index);
    }

    public void setFirstEnabledIndex() {
        final EnabledComboBoxModel model = (EnabledComboBoxModel) this.getModel();
        if (model == null) {
            return;
        }
        model.setFirstEnabledIndex();
    }

    private class ComboListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent e) {
            final int index = EnabledComboBox.this.getSelectedIndex();
            if (index == -1) {
                return;
            }
            if (EnabledComboBox.this.isEnabled(index)) {
                EnabledComboBox.this.setSelectedIndex(index);
                for (final ActionListener l : EnabledComboBox.this.actionListeners) {
                    l.actionPerformed(e);
                }
            }
        }
    }
}
